package sh.service.impl;

import sh.orm.SessionFactory;
import sh.orm.query.Condition;
import sh.orm.query.ConditionConst;
import sh.orm.query.QueryCondition;
import sh.model.User;
import sh.service.UserService;
import sh.util.BizException;
import sh.orm.util.HttpConst;
import sh.util.SessionUtil;

import java.util.List;

public class UserServiceImpl implements UserService {

	@Override
	public boolean add(User user)  {

		SessionFactory.getInstance().getSession().save(user);

		return true;
	}

	@Override
	public User get(Long id) {
		return SessionFactory.getInstance().getSession().getById(id, User.class);
	}

	@Override
	public List<User> getAllUsers(){
		return SessionFactory.getInstance().getSession().getAll( User.class);
	}
	
	@Override
	public boolean changePassword(Long userId , String newPassword){
		User user = SessionFactory.getInstance().getSession().getById(userId ,User.class);
		if(user == null){
			throw new BizException(userId + "用户不存在");
		}
		user.setPassword(newPassword);
		SessionFactory.getInstance().getSession().update(user);
		return true ;
	}

	@Override
	public boolean myLogin(User user){

		QueryCondition queryCondition = new QueryCondition();
		Condition condition = new Condition(User.USER_NAME , ConditionConst.EQUAL , user.getUserName());
		Condition condition2 = new Condition(User.PASSWORD , ConditionConst.EQUAL , user.getPassword());
		queryCondition.add(condition)
				.add(condition2);
		List<User> userList = SessionFactory.getInstance().getSession().selectByQueryCondition(queryCondition ,User.class);
		if(userList == null || userList.size() < 1){
			return false;
		}
		User u = userList.get(0);
		SessionUtil.getSession().setAttribute(HttpConst.SESSION_CURRENT_USER,u);
		return true;
	}
}
